package com.artron.mediaartron.ui.fragment.center;


import android.os.Bundle;
import android.support.design.widget.BottomSheetDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.artron.baselib.adapter.recyclerview.BaseViewHolder;
import com.artron.baselib.adapter.recyclerview.CommonAdapter;
import com.artron.baselib.adapter.recyclerview.DividerItemDecoration;
import com.artron.baselib.adapter.recyclerview.LoadMoreWrapper;
import com.artron.baselib.adapter.recyclerview.MultiItemTypeAdapter;
import com.artron.baselib.base.BaseLoadingFragment;
import com.artron.baselib.entity.Response;
import com.artron.baselib.utils.UIUtils;
import com.artron.baselib.utils.UIUtils.ColorText;
import com.artron.mediaartron.R;
import com.artron.mediaartron.data.callback.PayCallback;
import com.artron.mediaartron.data.config.AppProfile;
import com.artron.mediaartron.data.entity.AliPayResult;
import com.artron.mediaartron.data.entity.OrderContentData;
import com.artron.mediaartron.data.entity.OrderContentData.OrderListBean;
import com.artron.mediaartron.data.entity.WeChatData;
import com.artron.mediaartron.data.net.RetrofitHelper;
import com.artron.mediaartron.data.production.SuitableSizeHelper;
import com.artron.mediaartron.ui.activity.GeneralActivity;
import com.artron.mediaartron.ui.adapter.LoadMoreListener;
import com.artron.mediaartron.ui.fragment.dialog.NormalDialogFragment;
import com.artron.mediaartron.ui.helper.ThrottleFirstClickHelper;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.SimpleMultiPurposeListener;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.analytics.MobclickAgent;

import java.util.List;
import java.util.Map;

import butterknife.BindView;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

import static com.artron.mediaartron.data.production.FrameConstant.BLANK_CUSTOM_MADE;
import static com.artron.mediaartron.ui.fragment.order.OrderDetailFragment.*;
import static com.artron.mediaartron.ui.fragment.order.OrderDetailFragment.CANCEL;
import static com.artron.mediaartron.ui.fragment.order.OrderDetailFragment.NOT_PAY;
import static com.artron.mediaartron.ui.fragment.order.OrderDetailFragment.PAY_FINISH;
import static com.artron.mediaartron.ui.fragment.order.OrderDetailFragment.PAY_MAKE;
import static com.umeng.analytics.pro.x.S;


/**
 * Class description here
 *
 * @author doing
 * @version 1.0.0
 * @since 2017-11-02.
 */

public class MyOrderContentFragment extends BaseLoadingFragment<OrderContentData> {

    @BindView(R.id.MyOrderContentFragment_recycler)
    protected RecyclerView mRecyclerView;
    @BindView(R.id.MyOrderContentFragment_refresh)
    protected SmartRefreshLayout mRefreshLayout;
    private int mPosition;
    private ClassicsHeader mRefreshHeader;
    private List<OrderListBean> mOrderList;
    private CommonAdapter mAdapter;
    private LoadMoreWrapper mWrapper;

    public static MyOrderContentFragment newInstance(int position) {
        MyOrderContentFragment fragment = new MyOrderContentFragment();
        fragment.init(position);
        return fragment;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (mPosition == 0) {
            show();
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_my_order_content;
    }

    private void init(int position) {
        this.mPosition = position;
    }

    @Override
    protected void initVariable() {
        mRefreshHeader = new ClassicsHeader(mContext);
    }

    @PayModel
    private int getType(int status) {
        if (status == 1) {
            return NOT_PAY;
        } else if (status == -1) {
            return CANCEL;
        } else if (status >= 2 && status < 10) {
            return PAY_MAKE;
        } else {
            return PAY_FINISH;
        }
    }

    @Override
    protected void initView() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext,
                LinearLayoutManager.VERTICAL, false));
        mRecyclerView.addItemDecoration(new DividerItemDecoration(mContext,
                DividerItemDecoration.VERTICAL_LIST, R.drawable.shape_gray_f4f5f5_10dp));
    }

    @Override
    public void initViewWithData(OrderContentData data) {
        mOrderList = data.getOrderList();

        mRefreshLayout.finishRefresh();
        mAdapter = new CommonAdapter<OrderListBean>(mContext, R.layout.item_my_order_content, mOrderList) {

            private float mMeasuredHeight;

            @Override
            protected void convert(BaseViewHolder holder, OrderListBean data, int position) {

                List<OrderListBean.WorksListBean> list = data.getWorksList();
                if (list != null && list.size() != 0) {
                    LinearLayout parent = holder.getView(R.id.ItemMyOrderContent_ll_goods);
                    parent.removeAllViews();
                    int allQuantity = 0, allPrice = 0;
                    for (OrderListBean.WorksListBean bean : list) {
                        BaseViewHolder contentHolder = BaseViewHolder.createViewHolder(parent.getContext(),
                                parent, R.layout.layout_my_order_content);
                        String worksName = bean.getWorksName();
                        if (TextUtils.isEmpty(worksName)) {
                            worksName = "未命名";
                        }

                        resizeImageView(contentHolder, bean);

                        String type = "框画";
                        if ("haibao".equals(bean.getWorksTypeCode())) {
                            type = "海报";
                        }

                        contentHolder.setText(R.id.ItemMyOrderContent_tv_frame_name, worksName)
                                .setText(R.id.ItemMyOrderContent_tv_frame_type, type)
                                .setText(R.id.ItemMyOrderContent_tv_frame_shape, bean.getWorksShape())
                                .setText(R.id.ItemMyOrderContent_tv_frame_size, bean.getWorksSize() + "mm")
                                .setText(R.id.ItemMyOrderContent_tv_frame_num, "X" + bean.getWorksQuantity())
                                .setText(R.id.ItemMyOrderContent_tv_frame_price, "￥" + bean.getWorksPrice())
                                .setImageUrl(R.id.ItemMyOrderContent_iv_image, bean.getThumbnailPath());

                        parent.addView(contentHolder.getContentView());

                        allQuantity += bean.getWorksQuantity();
                        allPrice += bean.getWorksPrice() * bean.getWorksQuantity();
                    }
                    holder.setText(R.id.ItemMyOrderContent_tv_code, "订单号：" + data.getOrderCode())
                            .setText(R.id.ItemMyOrderContent_tv_type, data.getStatusName());

                    @PayModel int type = getType(data.getStatus());

                    holder.setOnClickListener(R.id.ItemMyOrderContent_tv_pay, new MyOnClickListener(data, holder))
                            .setTag(R.id.ItemMyOrderContent_tv_pay, type);

                    String priceText = "件商品 需付款：";
                    switch (type) {
                        case CANCEL:
                            holder.setText(R.id.ItemMyOrderContent_tv_pay, "删除订单")
                                    .setVisible(R.id.ItemMyOrderContent_tv_pay, View.VISIBLE)
                                    .setVisible(R.id.ItemMyOrderContent_tv_make, View.GONE)
                                    .setTextColorRes(R.id.ItemMyOrderContent_tv_pay, R.color.order_purple)
                                    .setBackgroundRes(R.id.ItemMyOrderContent_tv_pay, R.drawable.shape_purple_border)
                                    .setText(R.id.ItemMyOrderContent_tv_type, "已取消");

                            break;
                        case NOT_PAY:
                            holder.setText(R.id.ItemMyOrderContent_tv_pay, "去支付")
                                    .setVisible(R.id.ItemMyOrderContent_tv_pay, View.VISIBLE)
                                    .setVisible(R.id.ItemMyOrderContent_tv_make, View.GONE)
                                    .setTextColorRes(R.id.ItemMyOrderContent_tv_pay, R.color.order_purple)
                                    .setBackgroundRes(R.id.ItemMyOrderContent_tv_pay, R.drawable.shape_purple_border)
                                    .setText(R.id.ItemMyOrderContent_tv_type, "待付款");
                            break;
                        case PAY_FINISH:
                            holder.setText(R.id.ItemMyOrderContent_tv_pay, "查看物流")
                                    .setVisible(R.id.ItemMyOrderContent_tv_pay, View.VISIBLE)
                                    .setVisible(R.id.ItemMyOrderContent_tv_make, View.GONE)
                                    .setTextColorRes(R.id.ItemMyOrderContent_tv_pay, R.color.gray_33)
                                    .setBackgroundRes(R.id.ItemMyOrderContent_tv_pay, R.drawable.shape_gray_33_border)
                                    .setText(R.id.ItemMyOrderContent_tv_type, "已付款");
                            priceText = "件商品 实付款：";
                            break;
                        case PAY_MAKE:
                            holder.setVisible(R.id.ItemMyOrderContent_tv_pay, View.INVISIBLE)
                                    .setVisible(R.id.ItemMyOrderContent_tv_make, View.VISIBLE)
                                    .setBackgroundRes(R.id.ItemMyOrderContent_tv_pay, R.drawable.shape_gray_33_border)
                                    .setText(R.id.ItemMyOrderContent_tv_type, "已付款");
                            priceText = "件商品 实付款：";
                            break;
                    }
                    TextView tvAllPrice = holder.getView(R.id.ItemMyOrderContent_tv_all_price);
                    UIUtils.setTextWithColor(tvAllPrice,
                            ColorText.holder(UIUtils.getColor(R.color.gray_8a8c96), "共"),
                            ColorText.holder(UIUtils.getColor(R.color.gray_33), allQuantity + ""),
                            ColorText.holder(UIUtils.getColor(R.color.gray_8a8c96), priceText),
                            ColorText.holder(UIUtils.getColor(R.color.gray_33), "￥" + allPrice));
                }
            }

            private void resizeImageView(BaseViewHolder holder, OrderListBean.WorksListBean bean) {
                FrameLayout frameLayout = holder.getView(R.id.ItemMyOrderContent_fl_frame);
                if (frameLayout != null && mMeasuredHeight == 0) {
                    int height = frameLayout.getLayoutParams().height;
                    int spec = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY);
                    frameLayout.measure(spec, spec);
                    mMeasuredHeight = frameLayout.getMeasuredHeight();
                }

                ImageView imageView = holder.getView(R.id.ItemMyOrderContent_iv_image);
                String[] sizeArr = bean.getWorksSize().split("X");
                float width = Float.parseFloat(sizeArr[0]);
                float height = Float.parseFloat(sizeArr[1]);

                float per = mMeasuredHeight / Math.max(width, height);
                float layoutWidth = (width - BLANK_CUSTOM_MADE) * per;
                float layoutHeight = (height - BLANK_CUSTOM_MADE) * per;
                ViewGroup.LayoutParams params = imageView.getLayoutParams();
                params.height = (int) layoutHeight;
                params.width = (int) layoutWidth;
                imageView.setLayoutParams(params);
            }

            class MyOnClickListener implements View.OnClickListener {

                private final OrderListBean data;
                private final BaseViewHolder holder;
                private BottomSheetDialog payDialog;

                public MyOnClickListener(OrderListBean data, BaseViewHolder holder) {
                    this.data = data;
                    this.holder = holder;
                }

                @Override
                public void onClick(View v) {
                    switch (v.getId()) {
                        case R.id.ItemMyOrderContent_tv_pay:
                            @PayModel int type = (Integer) v.getTag();
                            switch (type) {
                                case CANCEL:
                                    NormalDialogFragment dialog = NormalDialogFragment.newInstance(
                                            "确认要刪除订单吗？", "再想想", "确定");
                                    dialog.setOnNegativeClickListener(new Action0() {
                                        @Override
                                        public void call() {
                                            int position = holder.getAdapterPosition();
                                            RetrofitHelper.subscript(RetrofitHelper.getOrderApi()
                                                            .recycleOrder(data.getOrderCode()),
                                                    new Action1<Response>() {
                                                        @Override
                                                        public void call(Response response) {
                                                            Log.d(TAG, "call: " + response);
                                                        }
                                                    });
                                            mOrderList.remove(data);
                                            mAdapter.deleteItem(position);
                                            mWrapper.notifyItemRemoved(position);
                                        }
                                    });
                                    dialog.show(getChildFragmentManager(), dialog.getOurTag());
                                    break;
                                case NOT_PAY:
                                    payDialog = new BottomSheetDialog(mContext);
                                    payDialog.setContentView(R.layout.layout_bottom_pay);

                                    payDialog.findViewById(R.id.LayoutBottomPay_ll_weixin).setOnClickListener( new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            payDialog.dismiss();
                                            ensurePay(false, data.getOrderCode(), data.getTotalPrice() + "", data.getOrderId());
                                        }
                                    });

                                    payDialog.findViewById(R.id.LayoutBottomPay_ll_zhifubao).setOnClickListener( new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            payDialog.dismiss();
                                            ensurePay(true, data.getOrderCode(), data.getTotalPrice() + "", data.getOrderId());

                                        }
                                    });

                                    payDialog.show();
                                    break;
                                case PAY_MAKE:

                                    break;
                                case PAY_FINISH:
                                    break;
                            }
                            break;
                    }
                }
            }
        };
        mAdapter.setOnItemClickListener(new MultiItemTypeAdapter.SimpleOnItemClickListener(){
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                OrderListBean bean = mOrderList.get(position);
                GeneralActivity.start(mContext, GeneralActivity.ORDER_DETAIL, "订单详情", bean.getOrderId());
            }
        });
        mWrapper = new LoadMoreWrapper(mAdapter);
        mWrapper.setLoadMoreView(R.layout.layout_loading_more);
        mWrapper.setOnLoadMoreListener(new LoadMoreListener<>(
                mOrderList, mWrapper, new Func1<Integer, Observable<Response<OrderContentData>>>() {
            @Override
            public Observable<Response<OrderContentData>> call(Integer integer) {
                return getResponseObservable(integer);
            }
        }
        ));
        mRecyclerView.setAdapter(mWrapper);

        mRefreshLayout.setRefreshHeader(mRefreshHeader);
        mRefreshLayout.setOnRefreshListener(new SimpleMultiPurposeListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                showImmediate();
            }
        });
    }

    private Observable<Response<OrderContentData>> getResponseObservable(Integer integer) {
        String passId = AppProfile.getUserInfo().getPassId();
        if (mPosition == 0) {
            return RetrofitHelper.getOrderApi().queryAllOrders(passId, integer, 10);
        }
        return RetrofitHelper.getOrderApi().queryOrders(passId, integer, 10, getRequestStatus(mPosition));
    }

    @Override
    protected Observable<Response<OrderContentData>> retrofitData() {
        return getResponseObservable(1);
    }

    @Override
    protected int getErrorViewId() {
        return R.layout.layout_my_order_content_empty;
    }

    /**
     * 1	-1	已取消	是
     * 2	1	已创建
     * 3	2	支付中
     * 4	3	已支付
     * 5	4	PDF 制作中
     * 6	5	PDF 制作完成
     * 7	6	推送给MES
     * 8	7	成功推送到MES
     * 9	8
     * 10	9
     * 11	10	已发货
     */
    private byte getRequestStatus(int position) {
        switch (position) {
            case 1:
                return 1;
            case 2:
                return 3;
            case 3:
                return -1;
        }
        return 0;
    }

    private Observable<Response<WeChatData>> getPayApi(boolean isZfbCheck, String orderCode, String totalPrice){
        if (isZfbCheck) {
            return RetrofitHelper.getHostApi().getAlipayData(orderCode,
                    totalPrice + "", "传媒雅昌")
                    .map(new Func1<Response<String>, Response<WeChatData>>() {
                        @Override
                        public Response<WeChatData> call(Response<String> response) {
                            Response<WeChatData> result = new Response<>();
                            WeChatData data = new WeChatData();
                            data.setAlipayStr(response.getData());
                            result.setData(data);
                            return result;
                        }
                    });
        } else {
            return RetrofitHelper.getHostApi().getWeChatData(orderCode,
                    totalPrice + "");
        }
    }//160428bdb557408686b919c85ac7162e 299  201711221626146639

    private void ensurePay(final boolean isZfbCheck, String orderCode, String totalPrice, final String orderId) {
        getPayApi(isZfbCheck, orderCode, totalPrice)
                .flatMap(new Func1<Response<WeChatData>, Observable<AliPayResult>>() {
                    @Override
                    public Observable<AliPayResult> call(Response<WeChatData> response) {
                        if (response == null || response.getData() == null) {
                            return null;
                        }

                        final WeChatData data = response.getData();
                        if (isZfbCheck) {
                            return Observable.create(new Observable.OnSubscribe<AliPayResult>() {
                                @Override
                                public void call(Subscriber<? super AliPayResult> subscriber) {
                                    try {
                                        PayTask aliPay = new PayTask(getActivity());
                                        String aliPayStr = data.getAlipayStr();
                                        Map<String, String> result = aliPay.payV2(aliPayStr, true);
                                        subscriber.onNext(new AliPayResult(result));
                                    } catch (Exception e) {
                                        MobclickAgent.reportError(UIUtils.getContext(), e);
                                        subscriber.onError(e);
                                    } finally {
                                        subscriber.onCompleted();
                                    }
                                }
                            });
                        } else {
                            SuitableSizeHelper.getHelper().setStartPayDetail(true);
                            SuitableSizeHelper.getHelper().setOrderId(orderId);
                            SuitableSizeHelper.getHelper().setNotStart(true);
                            IWXAPI wxApi = WXAPIFactory.createWXAPI(mContext, null);
                            wxApi.registerApp(data.getAppid());
                            PayReq request = new PayReq();
                            request.appId = data.getAppid();
                            request.partnerId = data.getMch_id();
                            request.prepayId = data.getPrepay_id();
                            request.packageValue = data.getPackageX();
                            request.nonceStr = data.getNonce_str();
                            request.timeStamp = data.getTimestamp() + "";
                            request.sign = data.getSecondSignature();
                            wxApi.sendReq(request);
                        }
                        return null;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Action1<AliPayResult>() {
                    @Override
                    public void call(AliPayResult result) {
                        if (result != null) {
                            if (result.getResult() != null
                                    && "9000".equals(result.getResultStatus())) {
                                PayCallback.startFinishPage(getActivity(), orderId, true, true, false);
                            } else {
                                PayCallback.startFinishPage(getActivity(), orderId, false, true, false);
                            }
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        MobclickAgent.reportError(UIUtils.getContext(), throwable);
                    }
                });
    }
}
